package com.example.demo.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

import com.baidu.translate.demo.TransApi;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class HttpUtil {

	
	public static String getHtml(String urlString) {
		StringBuilder response = new StringBuilder();
		
		HttpURLConnection connection = null;
		try {
			URL url = new URL(urlString);
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
			connection.setRequestProperty("User-Agent", "Mozilla/5.0"); // 设置合适的User-Agent头

			if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { // 检查响应码是否为200
			    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			    String inputLine;

			    while ((inputLine = in.readLine()) != null) {
			        response.append(inputLine);
			    }
			    in.close();
			} else {
			    System.out.println("请求失败，响应码: " + connection.getResponseCode());
			}

			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(connection != null){
				connection.disconnect(); // 关闭连接
			}
		}
        
        return response.toString(); // 输出HTML内容
	}
	
	public static String trans(String zhString) {
		TransApi api = new TransApi("20240105001932306", "Gkwser_uN703nbNWtb7N");

        String transResult = api.getTransResult(zhString, "en", "zh");
        System.out.println(transResult);
		
		Gson gson = new Gson();
		Map<String, Object> map = gson.fromJson(transResult, new TypeToken<Map<String, Object>>(){}.getType());
		List<Map<String, String>> trans_result = (List<Map<String, String>>) map.get("trans_result");
		if(trans_result != null && !trans_result.isEmpty()) {
			Map<String, String> trans_result0 = (Map<String, String>) trans_result.get(0);
			return trans_result0.get("dst");
		} else {
			return "";
		}
	}
}
